package main.database;

import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import main.GlobalConfig;
import main.Logman;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.Arrays;

public class RandomNameHelper {
    public static String fetchRandomNameNotUsed(boolean useImmdiately) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfUserNamePool);
        AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(Aggregates.sample(1), Aggregates.match(Filters.eq("used", false))));

        String result = null;
        MongoCursor<Document> cursor = documents.iterator();
        if (cursor.hasNext()) {
            Document doc = cursor.next();
            result = doc.get("name").toString();

            if (useImmdiately) {
                Bson filter = new Document("name", result);
                Bson newValue = new Document("used", true);
                Bson updateOperationDocument = new Document("$set", newValue);
                collection.updateOne(filter, updateOperationDocument);
            }
        }
        else {
            Logman.fatal("名字库里已经没有可以用的数据了");
        }

        return result;
    }
}
